package org.jivesoftware.smack;

import com.easemob.util.EMLog;
import java.io.PrintStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.packet.XMPPError.Condition;
import org.jivesoftware.smack.parsing.ParsingExceptionCallback;
import org.jivesoftware.smack.parsing.UnparsablePacket;
import org.jivesoftware.smack.sasl.SASLMechanism.Challenge;
import org.jivesoftware.smack.sasl.SASLMechanism.Failure;
import org.jivesoftware.smack.sasl.SASLMechanism.Success;
import org.jivesoftware.smack.util.PacketParserUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

class PacketReader
{
  private Thread readerThread;
  private ExecutorService listenerExecutor;
  private XMPPConnection connection;
  private XmlPullParser parser;
  volatile boolean done;
  private String connectionID = null;
  private boolean featuresAreParsed = false;

  protected PacketReader(XMPPConnection paramXMPPConnection)
  {
    this.connection = paramXMPPConnection;
    init();
  }

  protected void init()
  {
    this.done = false;
    this.connectionID = null;
    this.featuresAreParsed = false;
    this.readerThread = new Thread()
    {
      public void run()
      {
        PacketReader.this.parsePackets(this);
      }
    };
    this.readerThread.setName("Smack Packet Reader (" + this.connection.connectionCounterValue + ")");
    this.readerThread.setDaemon(true);
    this.listenerExecutor = Executors.newSingleThreadExecutor(new ThreadFactory()
    {
      public Thread newThread(Runnable paramAnonymousRunnable)
      {
        Thread localThread = new Thread(paramAnonymousRunnable, "Smack Listener Processor (" + PacketReader.this.connection.connectionCounterValue + ")");
        localThread.setDaemon(true);
        return localThread;
      }
    });
    resetParser();
  }

  public synchronized void startup()
    throws XMPPException
  {
    this.readerThread.start();
    try
    {
      int i = SmackConfiguration.getPacketReplyTimeout();
      wait(i);
    }
    catch (InterruptedException localInterruptedException)
    {
    }
    if (this.connectionID == null)
      throw new XMPPException("Connection failed. No response from server.");
    if (!this.featuresAreParsed)
      throw new XMPPException("Connection failed. The features are not received from server.");
    this.connection.connectionID = this.connectionID;
  }

  public void shutdown()
  {
    if (!this.done)
    {
      Iterator localIterator = this.connection.getConnectionListeners().iterator();
      while (localIterator.hasNext())
      {
        ConnectionListener localConnectionListener = (ConnectionListener)localIterator.next();
        try
        {
          localConnectionListener.connectionClosed();
        }
        catch (Exception localException)
        {
          localException.printStackTrace();
        }
      }
    }
    this.done = true;
    this.listenerExecutor.shutdown();
  }

  private void resetParser()
  {
    try
    {
      EMLog.d("packet reader", "enter resetParser");
      this.parser = XmlPullParserFactory.newInstance().newPullParser();
      this.parser.setFeature("http://xmlpull.org/v1/doc/features.html#process-namespaces", true);
      this.parser.setInput(this.connection.reader);
      EMLog.d("packet reader", "exit resetParser");
    }
    catch (XmlPullParserException localXmlPullParserException)
    {
      localXmlPullParserException.printStackTrace();
    }
  }

  private void parsePackets(Thread paramThread)
  {
    try
    {
      int i = this.parser.getEventType();
      label846: 
      do
      {
        if (i == 2)
        {
          int j = this.parser.getDepth();
          ParsingExceptionCallback localParsingExceptionCallback = this.connection.getParsingExceptionCallback();
          Object localObject;
          String str2;
          UnparsablePacket localUnparsablePacket;
          if (this.parser.getName().equals("message"))
          {
            try
            {
              localObject = PacketParserUtils.parseMessage(this.parser);
            }
            catch (Exception localException2)
            {
              str2 = PacketParserUtils.parseContentDepth(this.parser, j);
              localUnparsablePacket = new UnparsablePacket(str2, localException2);
              if (localParsingExceptionCallback == null)
                break label846;
            }
            localParsingExceptionCallback.handleUnparsablePacket(localUnparsablePacket);
            break label846;
            processPacket((Packet)localObject);
          }
          else if (this.parser.getName().equals("iq"))
          {
            try
            {
              localObject = PacketParserUtils.parseIQ(this.parser, this.connection);
            }
            catch (Exception localException3)
            {
              str2 = PacketParserUtils.parseContentDepth(this.parser, j);
              localUnparsablePacket = new UnparsablePacket(str2, localException3);
              if (localParsingExceptionCallback == null)
                break label846;
            }
            localParsingExceptionCallback.handleUnparsablePacket(localUnparsablePacket);
            break label846;
            processPacket((Packet)localObject);
          }
          else if (this.parser.getName().equals("presence"))
          {
            try
            {
              localObject = PacketParserUtils.parsePresence(this.parser);
            }
            catch (Exception localException4)
            {
              str2 = PacketParserUtils.parseContentDepth(this.parser, j);
              localUnparsablePacket = new UnparsablePacket(str2, localException4);
              if (localParsingExceptionCallback == null)
                break label846;
            }
            localParsingExceptionCallback.handleUnparsablePacket(localUnparsablePacket);
            break label846;
            processPacket((Packet)localObject);
          }
          else if (this.parser.getName().equals("stream"))
          {
            if ("jabber:client".equals(this.parser.getNamespace(null)))
              for (int k = 0; k < this.parser.getAttributeCount(); k++)
                if (this.parser.getAttributeName(k).equals("id"))
                {
                  this.connectionID = this.parser.getAttributeValue(k);
                  if (!"1.0".equals(this.parser.getAttributeValue("", "version")))
                    releaseConnectionIDLock();
                }
                else if (this.parser.getAttributeName(k).equals("from"))
                {
                  this.connection.config.setServiceName(this.parser.getAttributeValue(k));
                }
          }
          else
          {
            if (this.parser.getName().equals("error"))
              throw new XMPPException(PacketParserUtils.parseStreamError(this.parser));
            if (this.parser.getName().equals("features"))
            {
              parseFeatures(this.parser);
            }
            else if (this.parser.getName().equals("proceed"))
            {
              this.connection.proceedTLSReceived();
              resetParser();
            }
            else
            {
              String str1;
              if (this.parser.getName().equals("failure"))
              {
                str1 = this.parser.getNamespace(null);
                if ("urn:ietf:params:xml:ns:xmpp-tls".equals(str1))
                  throw new Exception("TLS negotiation has failed");
                if ("http://jabber.org/protocol/compress".equals(str1))
                {
                  this.connection.streamCompressionDenied();
                }
                else
                {
                  SASLMechanism.Failure localFailure = PacketParserUtils.parseSASLFailure(this.parser);
                  processPacket(localFailure);
                  this.connection.getSASLAuthentication().authenticationFailed();
                }
              }
              else if (this.parser.getName().equals("challenge"))
              {
                str1 = this.parser.nextText();
                processPacket(new SASLMechanism.Challenge(str1));
                this.connection.getSASLAuthentication().challengeReceived(str1);
              }
              else if (this.parser.getName().equals("success"))
              {
                processPacket(new SASLMechanism.Success(this.parser.nextText()));
                this.connection.packetWriter.openStream();
                resetParser();
                this.connection.getSASLAuthentication().authenticated();
              }
              else if (this.parser.getName().equals("compressed"))
              {
                this.connection.startStreamCompression();
                resetParser();
              }
            }
          }
        }
        else if ((i == 3) && (this.parser.getName().equals("stream")))
        {
          this.connection.disconnect();
        }
        i = this.parser.next();
        EMLog.d("packet reader", "done is " + this.done + " eventType = " + i);
        if ((this.done) || (i == 1))
          break;
      }
      while (paramThread == this.readerThread);
    }
    catch (Exception localException1)
    {
      if ((!this.done) && (!this.connection.isSocketClosed()))
        this.connection.notifyConnectionError(localException1);
    }
  }

  private synchronized void releaseConnectionIDLock()
  {
    notify();
  }

  private void processPacket(Packet paramPacket)
  {
    if (paramPacket == null)
      return;
    Iterator localIterator = this.connection.getPacketCollectors().iterator();
    while (localIterator.hasNext())
    {
      PacketCollector localPacketCollector = (PacketCollector)localIterator.next();
      localPacketCollector.processPacket(paramPacket);
    }
    this.listenerExecutor.submit(new ListenerNotification(paramPacket));
  }

  private void parseFeatures(XmlPullParser paramXmlPullParser)
    throws Exception
  {
    int i = 0;
    boolean bool = false;
    int j = 0;
    while (j == 0)
    {
      int k = paramXmlPullParser.next();
      if (k == 2)
      {
        if (paramXmlPullParser.getName().equals("starttls"))
        {
          i = 1;
        }
        else if (paramXmlPullParser.getName().equals("mechanisms"))
        {
          this.connection.getSASLAuthentication().setAvailableSASLMethods(PacketParserUtils.parseMechanisms(paramXmlPullParser));
        }
        else if (paramXmlPullParser.getName().equals("bind"))
        {
          this.connection.getSASLAuthentication().bindingRequired();
        }
        else if (paramXmlPullParser.getName().equals("ver"))
        {
          this.connection.getConfiguration().setRosterVersioningAvailable(true);
        }
        else if (paramXmlPullParser.getName().equals("c"))
        {
          String str1 = paramXmlPullParser.getAttributeValue(null, "node");
          String str2 = paramXmlPullParser.getAttributeValue(null, "ver");
          if ((str2 != null) && (str1 != null))
          {
            String str3 = str1 + "#" + str2;
            this.connection.setServiceCapsNode(str3);
          }
        }
        else if (paramXmlPullParser.getName().equals("session"))
        {
          this.connection.getSASLAuthentication().sessionsSupported();
        }
        else if (paramXmlPullParser.getName().equals("compression"))
        {
          this.connection.setAvailableCompressionMethods(PacketParserUtils.parseCompressionMethods(paramXmlPullParser));
        }
        else if (paramXmlPullParser.getName().equals("register"))
        {
          this.connection.getAccountManager().setSupportsAccountCreation(true);
        }
      }
      else if (k == 3)
        if (paramXmlPullParser.getName().equals("starttls"))
          this.connection.startTLSReceived(bool);
        else if ((paramXmlPullParser.getName().equals("required")) && (i != 0))
          bool = true;
        else if (paramXmlPullParser.getName().equals("features"))
          j = 1;
    }
    this.featuresAreParsed = true;
    if ((!this.connection.isSecureConnection()) && (i == 0) && (this.connection.getConfiguration().getSecurityMode() == ConnectionConfiguration.SecurityMode.required))
      throw new XMPPException("Server does not support security (TLS), but security required by connection configuration.", new XMPPError(XMPPError.Condition.forbidden));
    if ((i == 0) || (this.connection.getConfiguration().getSecurityMode() == ConnectionConfiguration.SecurityMode.disabled))
      releaseConnectionIDLock();
  }

  private class ListenerNotification
    implements Runnable
  {
    private Packet packet;

    public ListenerNotification(Packet arg2)
    {
      Object localObject;
      this.packet = localObject;
    }

    public void run()
    {
      Iterator localIterator = PacketReader.this.connection.recvListeners.values().iterator();
      while (localIterator.hasNext())
      {
        Connection.ListenerWrapper localListenerWrapper = (Connection.ListenerWrapper)localIterator.next();
        try
        {
          localListenerWrapper.notifyListener(this.packet);
        }
        catch (Exception localException)
        {
          System.err.println("Exception in packet listener: " + localException);
          localException.printStackTrace();
        }
      }
    }
  }
}

/* Location:           D:\hygieia\userclient\common\libs\easemobchat_2.1.8.jar
 * Qualified Name:     org.jivesoftware.smack.PacketReader
 * JD-Core Version:    0.6.1
 */